﻿using M_Quality.API.Application.Command.QualitygroupCommand;
using M_Quality.API.Application.Command.RawMaterialQualityCommand;
using M_Quality.Domain;
using M_Quality.Repository.Impl;
using M_Quality.Repository.Interface;
using MediatR;

namespace M_Quality.API.Application.CommandHandler.RawMaterialQualityCommandHandler
{
    public class BackfillSpectionCommandHandler : IRequestHandler<BackfillSpectionCommand, List< Qualityinspection>>
    {
        protected readonly IQualityinspectionRepository qualityinspectionRepository;
        protected readonly IQualityprogromRepositry IQualityprogromRepositry;
        protected readonly IQualityPlanRepositry qualityPlanRepositry;

        public BackfillSpectionCommandHandler(IQualityinspectionRepository qualityinspectionRepository, IQualityprogromRepositry iQualityprogromRepositry, IQualityPlanRepositry qualityPlanRepositry)
        {
            this.qualityinspectionRepository = qualityinspectionRepository;
            IQualityprogromRepositry = iQualityprogromRepositry;
            this.qualityPlanRepositry = qualityPlanRepositry;
        }

        public async Task<List<Qualityinspection>> Handle(BackfillSpectionCommand request, CancellationToken cancellationToken)
        {
          
            var id = await qualityPlanRepositry.GetAsync(o => o.QualityPlanName == request.QualityPlanName);
            var ids = await IQualityprogromRepositry.GetAsync(o => o.QualityPlanCode == id.FirstOrDefault().QualityPlanCode);
            var res = await qualityinspectionRepository.GetAllAsync();
            // 使用 LINQ 的 Contains 方法来筛选
            var matchedInspections = res.Where(inspection => ids.Any(idItem => idItem.QualityinspectionId == inspection.QualityinspectionId)).ToList();
            return matchedInspections;


        }
    }
}
